package vue.spring.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginFilter
 * @Deccription TODO
 * @Author DZ
 * @Date 2020/6/6 23:49
 **/
@Component
public class LoginFilter extends ZuulFilter {

    // 可选值：pre，路由之前，routing：路由之时，post：路由之后，error：发送错误调用
    @Override
    public String filterType() {
        return "pre";
    }

    // 过滤顺序,数字越小，优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 过滤器的具体逻辑
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String token = request.getParameter("token");
        if (null == token) {
            context.setSendZuulResponse(false); // 拒绝访问
            context.setResponseStatusCode(401);// 没权限
            try {
                HttpServletResponse response = context.getResponse();
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("非法请求");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
